package com.example.mbb;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import prof.MbbClient;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import domain.MbbData;

public class MainActivity extends Activity {

	private MbbClient _mbbClient=new MbbClient();
	private static final String TAG="MBB_APP_MAIN_ACTIVITIY";
	private Timer _timer;
	private TimerTask _doAsynchronousTask;

	/*
		<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
		<uses-permission android:name="android.permission.INTERNET"/>
	 */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		registerListener(R.id.button1);


		//		NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		//		Notification notifyDetails = new Notification(R.drawable.ic_launcher,"New Alert, Click Me!",System.currentTimeMillis());
		//		Context context = getApplicationContext();
		//		CharSequence contentTitle = "Notification Details...";
		//		CharSequence contentText = "Browse Android Official Site by clicking me";
		//
		//		Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
		//		PendingIntent intent = PendingIntent.getActivity(MainActivity.this, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
		//
		//		notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
		//		mNotificationManager.notify(123, notifyDetails);

		// Prepare intent which is triggered if the
		// notification is selected
		Intent intent = new Intent(this, MainActivity.class);
		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

		// Build notification
		// Actions are just fake
		Notification noti = new NotificationCompat.Builder(this)
		.setContentTitle("New Announcement")
		.setContentText("Click to view").setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true).setTicker("qwertyuiopasdfghjkl1234567890zxcvbnm")
		.setContentIntent(pIntent).build();
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		// Hide the notification after its selected
		//noti.flags |= Notification.FLAG_AUTO_CANCEL;

		notificationManager.notify(0, noti);

	}

	private void registerListener(int iButtonId){
		Button button=(Button) findViewById(iButtonId);
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View iV) {
				disableButton(R.id.button1);
				toCallAsynchronous();
			}
		});
	}

	private void disableButton(int iButtonId){
		Button button=(Button) findViewById(iButtonId);
		button.setClickable(false);
	}

	private void enableButton(int iButtonId){
		Button button=(Button) findViewById(iButtonId);
		button.setClickable(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onPause() {
		Log.i(TAG, "onPause");
		//		if(_timer!=null){
		//			_timer.cancel();
		//			_timer.purge();
		//		}
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.i(TAG, "onResume");
		//		enableButton(R.id.button1);
		//		TableLayout table = (TableLayout) findViewById(R.id.myTable);
		//		table.removeAllViews();
		super.onResume();
	}

	@Override
	protected void onStop() {
		Log.i(TAG, "onStop");
		if(_timer!=null){
			_timer.cancel();
			_timer.purge();
		}
		finish();
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "onDestroy");
		if(_timer!=null){
			_timer.cancel();
			_timer.purge();
		}
		super.onDestroy();
	}

	@Override
	protected void onRestart() {
		Log.i(TAG, "onRestart");
		enableButton(R.id.button1);
		TableLayout table = (TableLayout) findViewById(R.id.myTable);
		table.removeAllViews();
		super.onRestart();
	}



	public void toCallAsynchronous() {
		final Handler handler = new Handler();
		if(_timer!=null){
			_timer.cancel();
			_timer.purge();
		}
		_timer = new Timer();
		_doAsynchronousTask = new TimerTask() {
			@Override
			public void run() {
				handler.post(new Runnable() {
					public void run() {
						Log.i(TAG, "isNetworkConnected()="+isNetworkConnected());
						if(isNetworkConnected()){
							try {
								//PostAsyncTask class that extends AsyncTask 
								PostAsyncTask thePostAsyncTask = new PostAsyncTask();
								thePostAsyncTask.execute();
							} catch (IllegalStateException e) {
								e.printStackTrace();
							}
						}
					}
				});
			}
		};
		//execute in every 10 sec
		_timer.schedule(_doAsynchronousTask, 0,10000);
	}


	/**
	 * Check the network state
	 * @return true if the phone is connected
	 */
	public boolean isNetworkConnected() {
		final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
		return (activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED);
	}


	private class PostAsyncTask extends AsyncTask<String, Void, String>{
		List<MbbData> _list=null;

		@Override
		protected String doInBackground(String... iParams) {
			MbbData theMbbData=new MbbData();
			theMbbData.setInfoTime("2012-10-29 11:40:37");
			_list=_mbbClient.selectData(theMbbData);
			return "Completed";
		}

		@Override
		protected void onPostExecute(String result) {
			SimpleDateFormat sdf=new SimpleDateFormat("hh:mm a\t\tdd-MMM-yy");
			TableLayout table = (TableLayout) findViewById(R.id.myTable);
			Log.i(TAG, result);
			table.removeAllViews();
			for(MbbData aRow:_list){
				TableRow row=new TableRow(MainActivity.this);
				row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
				TextView col=new TextView(MainActivity.this);
				col.setText(sdf.format(aRow.getInfoTimeDate()));
				col.setPadding(5,1,5,1);
				//			col.setBackgroundColor(Color.GRAY);
				row.addView(col);
				table.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

				row=new TableRow(MainActivity.this);
				//			row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
				col=new TextView(MainActivity.this);
				// in setText(var) - if var is Integer it thinks that you are trying to set the text with
				// a String resource with ID = the value of var. So always use toString() 
				col.setText("Teacher Id="+aRow.getTeacherId().toString());
				col.setPadding(5,1,5,1);
				row.addView(col);
				col=new TextView(MainActivity.this);
				col.setText("Course Id="+aRow.getCourseId().toString());
				col.setPadding(5,1,5,1);
				row.addView(col);
				table.addView(row);

				row=new TableRow(MainActivity.this);
				row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
				col=new TextView(MainActivity.this);
				col.setText("Info="+aRow.getInfoDetails());
				col.setPadding(5,1,5,20);
				row.addView(col);
				table.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
			}
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}

	}




}

